/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.cachepool.extend.connection.datasource;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.hibernate.cfg.Environment;

/**
 * <p>
 * NamingHelper.java
 * </p>
 * 
 * @author Jon.King 2007-5-9
 */
public final class NamingHelper {

    private static final Logger log = Logger.getLogger(NamingHelper.class);

    private NamingHelper() {
    }

    public static InitialContext getInitialContext(Properties props) throws NamingException {
        Hashtable<Object, Object> hash = getJndiProperties(props);
        log.info("JNDI InitialContext properties:" + hash);
        try {
            return (hash.size() == 0) ? new InitialContext() : new InitialContext(hash);
        } catch (NamingException e) {
            log.error("Could not obtain initial context", e);
            throw e;
        }
    }

    /**
     * Transform JNDI properties passed in the form <tt>hibernate.jndi.*</tt>
     * to the format accepted by <tt>InitialContext</tt> by triming the leading "<tt>hibernate.jndi</tt>".
     */
    public static Properties getJndiProperties(Properties properties) {
        HashSet<String> specialProps = new HashSet<String>();
        specialProps.add(Environment.JNDI_CLASS);
        specialProps.add(Environment.JNDI_URL);

        Properties result = new Properties();
        for (Iterator<Object> iter = properties.keySet().iterator(); iter.hasNext();) {
            String prop = (String) iter.next();
            if (prop.indexOf(Environment.JNDI_PREFIX) > -1 && !specialProps.contains(prop)) {
                result.setProperty(prop.substring(Environment.JNDI_PREFIX.length() + 1), properties.getProperty(prop));
            }
        }

        String jndiClass = properties.getProperty(Environment.JNDI_CLASS);
        String jndiURL = properties.getProperty(Environment.JNDI_URL);
        // we want to be able to just use the defaults, if JNDI environment properties are not supplied. So don't put null in anywhere
        if (jndiClass != null)
            result.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass);
        if (jndiURL != null)
            result.put(Context.PROVIDER_URL, jndiURL);

        return result;
    }
}
